﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using AuctionClassLibrary;
using System.Runtime.Serialization.Formatters.Binary;

namespace Server
{
    public delegate void HammerTimeDelegate();
    [Serializable]
    internal class ServerThread
    {
        private GetDataFromDatabase data;
        private List<Auction> auctions;
        private int _i; //auction index in list
        public HammerTimeDelegate HammeTimeEvent;
        private ServerMonitor _monitor;
        private DateTime _lastTime;
        private decimal _lastbid;
        private bool _sold;
        private BinaryFormatter _bf;

        private string _name;
        private string _bidName;

        public ServerThread(ServerMonitor monitor)
        {
            _monitor = monitor;
            data = new GetDataFromDatabase();
            auctions = data.GetProducts();
            //auctions = new List<Auction>
            //    {
            //        new Auction("Bananer", 10, 20, DateTime.Now, DateTime.Now, false, "ikke brugt"),
            //        new Auction("Sokker", 100, 200, DateTime.Now, DateTime.Now, false, "ikke brugt"),
            //        new Auction("Stok", 150, 300, DateTime.Now, DateTime.Now, false, "ikke brugt")
            //    };
            _i = 0;
            _lastbid = auctions[_i].StartPrice;
            _sold = false;
            _bidName = "ingen";
        }

        public void Handle(Socket clientSocket)
        {
            string data;
            string[] msg;
            NetworkStream _networkStream = new NetworkStream(clientSocket);
            StreamReader _streamReader = new StreamReader(_networkStream);
            StreamWriter _streamWriter = new StreamWriter(_networkStream);
            _name = _streamReader.ReadLine();
            _monitor.AddNetworkStreamAndStreamWriter(_networkStream, _streamWriter, _name);

            _bf = new BinaryFormatter();

            while (true)
            {
                try
                {
                    data = _streamReader.ReadLine();
                    msg = data.Split(';');
                    _name = msg[0];
                    switch (msg[msg.Length - 1])
                    {
                        case "login":
                            _bf.Serialize(_networkStream, auctions[_i]);
                            _streamWriter.WriteLine(_lastbid.ToString());
                            _streamWriter.Flush();
                            _monitor.BroadCastMessage(_monitor.NameList.Count.ToString() + ";count");
                            break;
                        case "bid":
                            _bidName = msg[0];
                            _lastTime = DateTime.Now;
                            _lastbid = decimal.Parse(msg[1]);
                            _monitor.BroadcastBid(_name, msg[1]);
                            break;
                        case "logout":
                            break;
                    }
                }
                catch (Exception) { break; }
            }

            _monitor.RemoveNetworkStreamAndStreamWriter(_networkStream, _streamWriter, _name);
            _monitor.BroadCastMessage(_monitor.NameList.Count.ToString() + ";count");
            _streamReader.Close();
            _streamWriter.Close();
            _networkStream.Close();
        }

        public void HammerTimeHandle()
        {
            _lastTime = DateTime.Now;
            while (!_sold && _i < auctions.Count)
            {
                DateTime now = DateTime.Now;
                TimeSpan diff = now - _lastTime;

                switch ((int)diff.TotalSeconds)
                {
                    case 10:
                        _monitor.BroadCastMessage("1.;hammer");
                        break;
                    case 20:
                        _monitor.BroadCastMessage("2.;hammer");
                        break;
                    case 30:
                        _monitor.BroadCastMessage("3. - Solgt til " + _bidName + "!!!!!" + ";hammer3");
                        _bidName = "ingen";
                        auctions[_i].Sold = true; //take auction item
                        _sold = true;
                        _i++; //next auktion index
                        //opdater i db
                        Thread.Sleep(30000);
                        if (_i == auctions.Count)
                            break;
                        _monitor.BroadCastMessage("sold");
                        _monitor.BrocastObject(auctions[_i], _bf);
                        _lastbid = auctions[_i].StartPrice;
                        _lastTime = DateTime.Now;
                        _monitor.BroadcastBid(_lastbid.ToString());
                        _sold = false;
                        break;
                }
                Thread.Sleep(1000);
            }
        }
    }

}



